package com.excemly.library.service;

import com.excemly.library.entity.User;
import com.excemly.library.repository.UserRepository;
import org.springframework.stereotype.Service;
//用户业务逻辑类，提供 authenticate 方法（通过 UserRepository 查询用户）
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

@Service
public class UserService {

    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    // 添加用户查询和创建方法
    public boolean existsByUsername(String username) {
        return userRepository.existsByUsername(username);
    }

    public User findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    public User createUser(User user) {
        return userRepository.save(user);
    }

    public boolean existsById(Long id) {
        return userRepository.existsById(id);
    }

    public User findById(Long id) {
        return userRepository.findById(id).orElse(null);
    }

    public User updateUser(User user) {
        return userRepository.save(user);
    }

    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }

    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(UserService.class);

    public Page<User> findUsers(String keyword, Pageable pageable) {
        logger.info("Searching users with keyword: {}", keyword);
        Page<User> result;
        if (keyword != null && !keyword.isEmpty()) {
            result = userRepository.findByUsernameContainingOrEmailContaining(keyword, keyword, pageable);
            logger.info("Executing query with keyword: {}", keyword);
        } else {
            result = userRepository.findAll(pageable);
        }
        logger.info("Found {} users", result.getTotalElements());
        return result;
    }
}